python shutil

复制文件和文件夹

import shutil, os
# 拷贝文件,并更改文件名
shutil.copy('data/hello1.txt', 'data/hello123.txt')
# 拷贝目录以及子目录所有文件
shutil.copytree('data', 'data_backup')

文件和文件夹的移动和改名

shutil.move('data/data.bak', 'data_backup')
shutil.move('data/data.bak', 'data_backup/data.bak.bak')
Warning

1、注意移动文件时,要判断目的地是文件夹还是文件。
2、目的地是文件会被覆盖。
3、如果对应目录不存在,则会报错。

永久删除文件和文件夹

#删除对应文件
os.unlink(path)
#删除文件夹。文件夹必须为空。
os.rmdir(path)
#删除PATH 文件夹,包括对应子目录。
shutil.rmtree(path)

遍历所有目录

import os

for floderName, subfolders, filenames in os.walk('C:\\Windows'):
    print('The current folder is ' + floderName)
    for subfolder in subfolders:
        print('SUBFLODER OF ' + floderName + ': ' + subfolder)
    for filename in filenames:
        print('FILE INSIDEL ' + floderName + ': ' + filename)
    print('')

os.walk()函数被传入一个字符串值,即一个文件夹的路径。你可以在一个 for循环语句中使用os.walk()函数,遍历目录树,就像使用range()函数遍历一个范围的数字一样。不像range(),os.walk()在循环的每次迭代中,返回3 个值: 1.当前文件夹名称的字符串。 2.当前文件夹中子文件夹的字符串的列表。 3.当前文件夹中文件的字符串的列表。 所谓当前文件夹,是指 for 循环当前迭代的文件夹。程序的当前工作目录,不会因为os.walk()而改变。 就像你可以在代码for i in range(10):中选择变量名称i 一样,你也可以选择前面列出来的3 个字的变量名称。我通常使用foldername、subfolders 和filenames。

ZIP 压缩文件处理

查看 ZIP 文件

import zipfile, os

os.chdir('D:\\')  # move to the folder with example.zip
exampleZip = zipfile.ZipFile('CRT_LOG.zip')
print(exampleZip.namelist())
# View a file in the file list.
sapmInfo = exampleZip.getinfo('CRT_LOG/host192.168.10.111year2023mouth01day07port22hour_.log')
# Print one file Original size.
print(sapmInfo.file_size)
# Print compress_size .
print(sapmInfo.compress_size)
print(f"Compressed file is {round(sapmInfo.file_size / sapmInfo.compress_size, 2)}")
# Print compression ratio.
exampleZip.close()

解压缩 ZIP 文件

解压到当前目录

1、extractall 解压到当前目录。

import zipfile, os

os.chdir('D:\\')  # move to the folder with example.zip
exampleZip = zipfile.ZipFile('CRT_LOG.zip')
# View a file in the file list.
print(exampleZip.namelist())

exampleZip.extractall()
exampleZip.close()

2、解压到指定目录

exampleZip. extractall ('D:\\CRT_LOG')

解压单个文件到指定目录

 exampleZip. extract ('spam. txt')  
'C:\\spam.txt'  
 exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')  
'C:\\some\\new\\folders\\spam.txt'  
exampleZip.close()

传递给extract()的字符串,必须匹配namelist()返回的字符串列表中的一个。或者,你可以向 extract()传递第二个参数,将文件解压缩到指定的文件夹,而不是当前工作目录。如果第二个参数指定的文件夹不存在,Python 就会创建它。extract()的返回值是被压缩后文件的绝对路径。

创建和添加到 ZIP 文件

1、使用 ZipFile 函数传入' w' 参数。[1]

2、使用 write 方法第一个参数为文件名称。zipfile.ZIP_DEFLATED 这是一种压缩算法。[2]

import zipfile

os.chdir('D:\\')  # move to the folder with example.zip
newZip = zipfile.ZipFile('new.zip','w')
newZip.write('CRT_LOG/', compress_type=zipfile.ZIP_DEFLATED)
newZip.close()

Warning

注意如果使用'w'选项,会擦除所有zip 文件内容。
如果只是希望添加文件,则需要传入'a'参数

zipfile.ZipFile('new.zip','a')

更改文件名日期格式

#! python3
# renameDates.py - Renames filenames with American MM-DD-YYY date format
# to European DD-MM-YYYY.
import shutil, os, re

# Create a regular expression to match the US date.
datePattern = re.compile(r"""^(.*?)
    ((19|20)\d\d)-
    ((0|1)?\d)-
    ((0|1|2|3)?\d)
    (.*?)$
    """, re.VERBOSE)

os.chdir('D:\\CRT_LOG')
# TODO: Loop over the files in the working directory.
for amerFilename in os.listdir('.'):
    mo = datePattern.search(amerFilename)
    if mo == None:
        continue
    # Get the different parts of the filename.
    beforePart = mo.group(1)
    monthPart = mo.group(2)
    dayPart = mo.group(4)
    yearPart = mo.group(6)
    afterPart = mo.group(8)
    euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart

    # TODO: Get the full, absolute file paths.
    absWorkingDir = os.path.abspath('.')
    amerFilename = os.path.join(absWorkingDir, amerFilename)
    euroFilename = os.path.join(absWorkingDir, euroFilename)


    # Rename the files.
    print(f"Renameing {amerFilename} to {euroFilename}....")
    shutil.move(amerFilename, euroFilename)  # uncomment after testing

# TODO: Rename the files.

实践,自动更新所有 word 版本号

#! python3
# renameDates.py - Renames filenames with American MM-DD-YYY date format
# to European DD-MM-YYYY.
import shutil
import os
import re

# Create a regular expression to match the US date.
datePattern = re.compile(r"""^(.*?)
    (v0\.)(\d\d)
    (.*?)$
    """, re.VERBOSE)

FileDir = 'D:\\03-R6课程置换-KCP'
os.chdir(FileDir)
# TODO: Loop over the files in the working directory.
for amerFilename in os.listdir('.'):
    mo = datePattern.search(amerFilename)
    if mo is None:
        continue
    # Get the different parts of the filename.
    HeadFilename = mo.group(1)
    Master_Version = mo.group(2)
    Old_Version = int(mo.group(3))
    New_Version = int(mo.group(3)) + 1
    EndFilename = mo.group(4)
    Old_Name = HeadFilename + Master_Version + str(Old_Version) + EndFilename
    New_Name = HeadFilename + Master_Version + str(New_Version) + EndFilename

    absWorkingDir = os.path.abspath('.')
    oldFilename = os.path.join(absWorkingDir, Old_Name)
    newFilename = os.path.join(absWorkingDir, New_Name)

    #    # Rename the files.
    print(f"Renaming {oldFilename} to {newFilename}....")
    shutil.move(oldFilename, newFilename)  # uncomment after testing


  1. 创建你自己的压缩ZIP 文件,必须以“写模式”打开ZipFile 对象,即传入'w'作为第二个参数(这类似于向open()函数传入'w',以写模式打开一个文本文件) ↩︎

  2. 如果向 ZipFile 对象的 write()方法传入一个路径,Python 就会压缩该路径所指的文件,将它加到 ZIP 文件中。write()方法的第一个参数是一个字符串,代表要添加的文件名。第二个参数是“压缩类型”参数,它告诉计算机使用怎样的算法来压缩文件。可以总是将这个值设置为 zipfile.ZIP_DEFLATED(这指定了 deflate 压缩算法,它对各种类型的数据都很有效)。 ↩︎